package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;
//自动补货工单处理

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
            //1-解析协议类容
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if(supplyContract==null){
            return;
        }
        //2-找出被指派人
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        var  userId= taskService.getLeastUser(vmInfo.getRegionId(), false);

        //3-创建补货工单
        TaskViewModel tvm = new TaskViewModel();
        tvm.setUserId(userId);
        tvm.setCreateType(0);
        tvm.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        tvm.setInnerCode(supplyContract.getInnerCode());
        tvm.setDesc("自动补货工单");
        tvm.setDetails(supplyContract.getSupplyData().stream().map(c->{
            TaskDetailsViewModel tdvm = new TaskDetailsViewModel();
            tdvm.setChannelCode(c.getChannelId());
            tdvm.setExpectCapacity(c.getCapacity());
            tdvm.setSkuId(c.getSkuId());
            tdvm.setSkuName(c.getSkuName());
            tdvm.setSkuImage(c.getSkuImage());
            return  tdvm;
        }).collect(Collectors.toList()));
        taskService.productionOrderSave(tvm);

    }
}
